// 引入Vue
import Vue from 'vue';

// 自定义拖拽指令
// Vue.directive('drag-control', {
// 	// 当绑定元素被插入到DOM中时
// 	inserted(el, binding, vnode) {
// 		let dragging = false;
// 		let mouseOffset = {};
// 		let startX, startY;

// 		// 当鼠标按下时
// 		el.onmousedown = function(e) {
// 			dragging = true;
// 			startX = e.clientX - el.offsetLeft;
// 			startY = e.clientY - el.offsetTop;
// 			mouseOffset = {
// 				x: startX,
// 				y: startY
// 			};
// 			document.onmousemove = function(e) {
// 				if (dragging) {
// 					const dx = e.clientX - mouseOffset.x;
// 					const dy = e.clientY - mouseOffset.y;
// 					var viewportWidth = window.innerWidth;
// 					var viewportHeight = window.innerHeight;
// 					el.style.left = `${dx*100/viewportWidth}%`;
// 					el.style.top = `${dy*100/viewportHeight}%`;
// 				}
// 			};

// 			e.preventDefault();
// 		};

// 		// 当鼠标松开时
// 		document.onmouseup = function() {
// 			dragging = false;
// 			document.onmousemove = null;
// 		};


// 	}
// });
Vue.directive('drag-control', {
	bind(el, binding, vnode) {
		let dragging = false;
		let mouseOffset = {};
		let startX, startY, offsetX, offsetY, left, top;

		el.style.position = 'absolute';

		const dragStart = (e) => {
			dragging = true;
			startX = e.touches[0].clientX;
			startY = e.touches[0].clientY;
			offsetX = el.offsetLeft;
			offsetY = el.offsetTop;
		};

		const dragMove = (e) => {
			if (dragging) {
				e.preventDefault();
				const dx = e.touches[0].clientX - startX;
				const dy = e.touches[0].clientY - startY;
				left = offsetX + dx;
				top = offsetY + dy;
				// el.style.left = left + 'px';
				// el.style.top = top + 'px';
				var viewportWidth = window.innerWidth;
				var viewportHeight = window.innerHeight;
				el.style.left = `${left*100/viewportWidth}%`;
				el.style.top = `${top*100/viewportHeight}%`;
			}
		};

		const dragEnd = (e) => {
			dragging = false;
		};

		el.addEventListener('touchstart', dragStart, false);
		el.addEventListener('touchmove', dragMove, false);
		el.addEventListener('touchend', dragEnd, false);

		vnode.elm.onTouchMove = dragMove;

		// 当鼠标按下时
		el.onmousedown = function(e) {
			dragging = true;
			startX = e.clientX - el.offsetLeft;
			startY = e.clientY - el.offsetTop;
			mouseOffset = {
				x: startX,
				y: startY
			};
			document.onmousemove = function(e) {
				if (dragging) {
					const dx = e.clientX - mouseOffset.x;
					const dy = e.clientY - mouseOffset.y;
					var viewportWidth = window.innerWidth;
					var viewportHeight = window.innerHeight;
					el.style.left = `${dx*100/viewportWidth}%`;
					el.style.top = `${dy*100/viewportHeight}%`;
				}
			};

			e.preventDefault();
		};

		// 当鼠标松开时
		document.onmouseup = function() {
			dragging = false;
			document.onmousemove = null;
		};
	},
	unbind(el, binding, vnode) {
		el.removeEventListener('touchstart', vnode.elm.onTouchStart);
		el.removeEventListener('touchmove', vnode.elm.onTouchMove);
		el.removeEventListener('touchend', vnode.elm.onTouchEnd);
	}
});